﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Data;
using System.Text;
using System.Xml;
using CE.InputOut;
using CE.Database;

/// <summary>
/// Summary description for MyFlight
/// </summary>
/// 
namespace CE.Wego
{
    public class MyFlight
    {
        const string API_KEY = "c08b4c9e";
        public MyFlight()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public DataSet CheckAPIUsage()
        {

            DataSet _ds = null;
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://www.wego.com/api/flights/usage.html? " + @"&apiKey=" + API_KEY + "&format=xml");
                //http://www.wego.com/api/flights/usage.html?format=json&apiKey=testAPIKey
                req.Method = "GET";
                req.Referer = "http://www.comparexpress.com";
                HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader answer = new StreamReader(stream);
                _ds = new DataSet("DsList");
                _ds.ReadXml(stream);
            }
            catch (WebException Wex)
            {
                CreateExceptionLog(Wex, "string CheckAPIUsage()");
            }
            catch (Exception Ex)
            {
                CreateExceptionLog(Ex, "string CheckAPIUsage()");
            }
            return _ds;

        }

        public DataSet SearchFlight(string fromLocation, string toLocation, string tripType, string cabinClass, string inboundDate, string outboundDate, string numAdults)
        {
            DataSet _ds = null;

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://www.wego.com/api/flights/startSearch.html? " + @"&apiKey=" + API_KEY + "&format=xml&"
                    + "fromLocation=" + fromLocation + "&toLocation=" + toLocation + "&tripType=" + tripType + "&cabinClass=" + cabinClass + "&inboundDate=" + inboundDate + "&outboundDate=" + outboundDate + "&numAdults=" + numAdults);
                //http://www.wego.com/api/flights/startSearch.html?format=json&fromLocation=SIN&toLocation=BKK&tripType=roundTrip&cabinClass=Economy&inboundDate=2010-06-26&outboundDate=2010-06-23&numAdults=1&apiKey=testApiKey
                req.Method = "GET";
                req.Referer = "http://www.comparexpress.com";
                HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader answer = new StreamReader(stream);
                _ds = new DataSet("DsList");
                _ds.ReadXml(stream);
            }
            catch (WebException Wex)
            {
                CreateExceptionLog(Wex, "string SearchFlight(string fromLocation, string toLocation, string tripType, string cabinClass, string inboundDate, string outboundDate, string numAdults)");
            }
            catch (Exception Ex)
            {
                CreateExceptionLog(Ex, "string SearchFlight(string fromLocation, string toLocation, string tripType, string cabinClass, string inboundDate, string outboundDate, string numAdults)");
            }
            return _ds;
        }

        public DataTable GetFlightResults(string instanceId)
        {
            string _result = "";
            DataTable _dtresult = new DataTable();

            try
            {
                //System.Threading.Thread.Sleep(10000);
                System.Threading.Thread.Sleep(5000);

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"http://www.wego.com/api/flights/pull.html? " + @"&apiKey=" + API_KEY + "&format=xml&instanceId=" + instanceId + "&rand=1");
                req.Method = "GET";
                req.Referer = "http://www.comparexpress.com";
                HttpWebResponse webResponse = (HttpWebResponse)req.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                StreamReader answer = new StreamReader(stream);
                _result = answer.ReadToEnd();

                _dtresult = CreateResultsTable();
                DataRow dr;
                
                string BookingCode = "";
                string Airlines = "";
                string LocationFrom = "";
                string LocationTo = "";
                string OutboundDepartureTime = "";
                string OutboundArrivalTime = "";
                string InboundDepartureTime = "";
                string InboundArrivalTime = "";
                string OutboundFlightNumber = "";
                string InboundFlightNumber = "";
                string OutboundAirport1 = "";
                string OutboundAirport2 = "";
                string InboundAirport1 = "";
                string InboundAirport2 = "";
                string OutboundDuration = "";
                string InboundDuration = "";
                string FareClassInbound = "";
                string FareClassOutbound = "";
                string PricePerPassenger = "";
                string TotalPrice = "";
                string IncludesTax = "";
                string Provider = "";
                string CurrencyCode = "";
                string Amount = "";
                string ID = "";
                string AirportFrom = "";
                string AirportTo = "";

                try
                {
                    XmlTextReader reader = new XmlTextReader(new StringReader(_result));
                    StringBuilder sb = new StringBuilder();

                    string fieldname = "";
                    bool isCarrier = false;
                    bool isInboundInfo = false;
                    bool isInboundAirport = false;
                    bool isInboundFlightClass = false;
                    bool isInboundFlightNos = false;
                    bool isOutboundInfo = false;
                    bool isOutboundAirport = false;
                    bool isOutboundFlightClass = false;
                    bool isOutboundFlightNos = false;
                    bool isLocation = false;
                    bool isLocationTo = false;

                    while (reader.Read())
                    {
                       
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            if (reader.Name == "bookingCode")
                            {
                                fieldname = "bookingCode";
                            }

                            if (reader.Name == "carrier")
                            {
                                isCarrier = true;
                            }

                            if (isCarrier && reader.Name == "name")
                            {
                                fieldname = "airlines";
                            }

                            if (reader.Name == "id")
                            {
                                fieldname = "ID";
                            }

                            //inboundinfo
                            if (reader.Name == "inboundInfo")
                            {
                                isInboundInfo = true;

                            }

                            if (isInboundInfo && reader.Name == "airports")
                            {
                                isInboundAirport = true;
                            }

                            if (isInboundInfo && isInboundAirport && reader.Name == "e")
                            {
                                if (fieldname == "InboundAirport1")
                                    fieldname = "InboundAirport2";
                                else
                                    fieldname = "InboundAirport1";
                            }

                            if (isInboundInfo && reader.Name == "durationInMin")
                            {
                                fieldname = "InboundDuration";
                            }

                            if (isInboundInfo && reader.Name == "flightClasses")
                            {
                                isInboundFlightClass = true;
                            }

                            if (isInboundInfo && isInboundFlightClass && reader.Name == "name")
                            {
                                fieldname = "FareClassInbound";
                            }

                            if (isInboundInfo && reader.Name == "flightNumbers")
                            {
                                isInboundFlightNos = true;
                            }

                            if (isInboundInfo && isInboundFlightNos && reader.Name == "e")
                            {
                                fieldname = "InboundFlightNumber";
                            }

                            if (isInboundInfo && reader.Name == "localArrivalTimeStr")
                            {
                                fieldname = "InboundArrivalTime";
                            }

                            if (isInboundInfo && reader.Name == "localDepartureTimeStr")
                            {
                                fieldname = "InboundDepartureTime";
                            }
                            //endinbound

                            if (reader.Name == "location")
                            {
                                isLocation = true;
                            }

                            if (isLocation && reader.Name == "name")
                            {
                                if (fieldname == "AirportTo")
                                {
                                    fieldname = "AirportFrom";
                                    isLocationTo = false;
                                }
                                else
                                {
                                    fieldname = "AirportTo";
                                    isLocationTo = true;
                                }
                            }

                            //outboundinfo
                            if (reader.Name == "outboundInfo")
                            {
                                isOutboundInfo = true;
                            }

                            if (isOutboundInfo && reader.Name == "airports")
                            {
                                isOutboundAirport = true;
                            }

                            if (isOutboundInfo && isOutboundAirport && reader.Name == "e")
                            {
                                if (fieldname == "OutboundAirport1")
                                    fieldname = "OutboundAirport2";
                                else
                                    fieldname = "OutboundAirport1";
                            }

                            if (isOutboundInfo && reader.Name == "durationInMin")
                            {
                                fieldname = "OutboundDuration";
                            }

                            if (isOutboundInfo && reader.Name == "flightClasses")
                            {
                                isOutboundFlightClass = true;
                            }

                            if (isOutboundInfo && isOutboundFlightClass && reader.Name == "name")
                            {
                                fieldname = "FareClassOutbound";
                            }

                            if (isOutboundInfo && reader.Name == "flightNumbers")
                            {
                                isOutboundFlightNos = true;
                            }

                            if (isOutboundInfo && isOutboundFlightNos && reader.Name == "e")
                            {
                                fieldname = "OutboundFlightNumber";
                            }

                            if (isOutboundInfo && reader.Name == "localArrivalTimeStr")
                            {
                                fieldname = "OutboundArrivalTime";
                            }

                            if (isOutboundInfo && reader.Name == "localDepartureTimeStr")
                            {
                                fieldname = "OutboundDepartureTime";
                            }
                            //endoutbound


                            if (reader.Name == "originCountryCode")
                            {
                                fieldname = "originCountryCode";
                            }

                            if (reader.Name == "destinationCountryCode")
                            {
                                fieldname = "destinationCountryCode";
                            }

                            if (reader.Name == "currencyCode")
                            {
                                fieldname = "currencyCode";
                            }

                            if (reader.Name == "amount")
                            {
                                fieldname = "amount";
                            }

                            if (reader.Name == "includesTax")
                            {
                                fieldname = "includesTax";
                            }

                            if (reader.Name == "pricePerPassenger")
                            {
                                fieldname = "pricePerPassenger";
                            }

                            if (reader.Name == "totalAmount")
                            {
                                fieldname = "totalAmount";
                            }


                            if (reader.Name == "providerId")
                            {
                                fieldname = "providerId";
                            }


                        }

                        if (reader.NodeType == XmlNodeType.Text)
                        {
                            if (fieldname == "bookingCode")
                            {
                                BookingCode = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "airlines")
                            {
                                Airlines = reader.ReadString();
                                fieldname = "";
                                isCarrier = false;
                            }

                            if (fieldname == "ID")
                            {
                                ID = reader.ReadString();
                                fieldname = "";
                            }

                            //inboundfields
                            if (fieldname == "InboundAirport1")
                            {
                                InboundAirport1 = reader.ReadString();
                            }

                            if (fieldname == "InboundAirport2")
                            {
                                InboundAirport2 = reader.ReadString();
                                fieldname = "";
                                isInboundAirport = false;
                            }

                            if (fieldname == "InboundDuration")
                            {
                                InboundDuration = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "FareClassInbound")
                            {
                                FareClassInbound = reader.ReadString();
                                fieldname = "";
                                isInboundFlightClass = false;
                            }

                            if (fieldname == "InboundFlightNumber")
                            {
                                InboundFlightNumber = reader.ReadString();
                                fieldname = "";
                                isInboundFlightNos = false;
                            }

                            if (fieldname == "InboundArrivalTime")
                            {
                                InboundArrivalTime = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "InboundDepartureTime")
                            {
                                InboundDepartureTime = reader.ReadString();
                                fieldname = "";
                                isInboundInfo = false;
                            }

                            //endinbound

                            //locationairportname
                            if (fieldname == "AirportTo" && isLocationTo)
                            {
                                AirportTo = reader.ReadString();
                                isLocationTo = false;
                            }

                            if (fieldname == "AirportFrom")
                            {
                                AirportFrom = reader.ReadString();
                                fieldname = "";
                                isLocation = false;
                            }

                            //outboundfields
                            if (fieldname == "OutboundAirport1")
                            {
                                OutboundAirport1 = reader.ReadString();
                            }

                            if (fieldname == "OutboundAirport2")
                            {
                                OutboundAirport2 = reader.ReadString();
                                fieldname = "";
                                isOutboundAirport = false;
                            }

                            if (fieldname == "OutboundDuration")
                            {
                                OutboundDuration = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "FareClassOutbound")
                            {
                                FareClassOutbound = reader.ReadString();
                                fieldname = "";
                                isOutboundFlightClass = false;
                            }

                            if (fieldname == "OutboundFlightNumber")
                            {
                                OutboundFlightNumber = reader.ReadString();
                                fieldname = "";
                                isOutboundFlightNos = false;
                            }

                            if (fieldname == "OutboundArrivalTime")
                            {
                                OutboundArrivalTime = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "OutboundDepartureTime")
                            {
                                OutboundDepartureTime = reader.ReadString();
                                fieldname = "";
                                isOutboundInfo = false;
                            }

                            //endoutbound

                            if (fieldname == "originCountryCode")
                            {
                                LocationFrom = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "destinationCountryCode")
                            {
                                LocationTo = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "amount")
                            {
                                Amount = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "currencyCode")
                            {
                                CurrencyCode = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "includesTax")
                            {
                                IncludesTax = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "pricePerPassenger")
                            {
                                PricePerPassenger = reader.ReadString();
                                fieldname = "";
                            }

                            if (fieldname == "totalAmount")
                            {
                                TotalPrice = reader.ReadString();
                                fieldname = "";
                            }


                            if (fieldname == "providerId")
                            {
                                Provider = reader.ReadString();
                                fieldname = "";
                            }

                        }

                        if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "itinerary")
                        {
                            dr = _dtresult.NewRow();

                            dr["BookingCode"] = BookingCode;
                            dr["ID"] = ID;
                            dr["Airlines"] = Airlines;
                            dr["LocationFrom"] = LocationFrom;
                            dr["LocationTo"] = LocationTo;
                            dr["AirportFrom"] = AirportFrom;
                            dr["AirportTo"] = AirportTo;
                            dr["OutboundDepartureTime"] = OutboundDepartureTime;
                            dr["OutboundArrivalTime"] = OutboundArrivalTime;
                            dr["InboundDepartureTime"] = InboundDepartureTime;
                            dr["InboundArrivalTime"] = InboundArrivalTime;
                            dr["OutboundFlightNumber"] = OutboundFlightNumber;
                            dr["InboundFlightNumber"] = InboundFlightNumber;
                            dr["OutboundAirport1"] = OutboundAirport1;
                            dr["OutboundAirport2"] = OutboundAirport2;
                            dr["InboundAirport1"] = InboundAirport1;
                            dr["InboundAirport2"] = InboundAirport2;
                            dr["OutboundDuration"] = OutboundDuration;
                            dr["InboundDuration"] = InboundDuration;
                            dr["FareClassInbound"] = FareClassInbound;
                            dr["FareClassOutbound"] = FareClassOutbound;
                            dr["PricePerPassenger"] = PricePerPassenger;
                            dr["TotalPrice"] = TotalPrice;
                            dr["Amount"] = Amount;
                            dr["CurrencyCode"] = CurrencyCode;
                            dr["IncludesTax"] = IncludesTax;
                            dr["Provider"] = Provider;

                            _dtresult.Rows.Add(dr);
                        }
                    }

                    reader.Close();

                }
                catch (XmlException xmlEx)
                {
                    xmlEx.ToString();
                    CreateExceptionLog(xmlEx, "ReadXML(string instanceId)");
                }

            }
            catch (WebException Wex)
            {
                CreateExceptionLog(Wex, "DataTable GetFlightResults(string instanceId)");
            }
            catch (Exception Ex)
            {
                CreateExceptionLog(Ex, "DataTable GetFlightResults(string instanceId)");
            }

            return _dtresult;
        }

        private DataTable CreateResultsTable()
        {
            DataTable dtWego = new DataTable();

            dtWego.Columns.Add("BookingCode", System.Type.GetType("System.String"));
            dtWego.Columns.Add("ID", System.Type.GetType("System.String"));
            dtWego.Columns.Add("Airlines", System.Type.GetType("System.String"));
            dtWego.Columns.Add("LocationFrom", System.Type.GetType("System.String"));
            dtWego.Columns.Add("LocationTo", System.Type.GetType("System.String"));
            dtWego.Columns.Add("AirportFrom", System.Type.GetType("System.String"));
            dtWego.Columns.Add("AirportTo", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundDepartureTime", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundArrivalTime", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundDepartureTime", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundArrivalTime", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundFlightNumber", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundFlightNumber", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundAirport1", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundAirport2", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundAirport1", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundAirport2", System.Type.GetType("System.String"));
            dtWego.Columns.Add("OutboundDuration", System.Type.GetType("System.String"));
            dtWego.Columns.Add("InboundDuration", System.Type.GetType("System.String"));
            dtWego.Columns.Add("FareClassInbound", System.Type.GetType("System.String"));
            dtWego.Columns.Add("FareClassOutbound", System.Type.GetType("System.String"));
            dtWego.Columns.Add("PricePerPassenger", System.Type.GetType("System.String"));
            dtWego.Columns.Add("TotalPrice", System.Type.GetType("System.String"));
            dtWego.Columns.Add("Amount", System.Type.GetType("System.String"));
            dtWego.Columns.Add("CurrencyCode", System.Type.GetType("System.String"));
            dtWego.Columns.Add("IncludesTax", System.Type.GetType("System.String"));
            dtWego.Columns.Add("Provider", System.Type.GetType("System.String"));



            return dtWego;
        }

        public string GetAirlineImage(string airlines)
        {
            string imagename = "";
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable("AirlineImage");
            string _spName = "sprocTAAirlineInfoSelectItem";
            SortedList _sPara = new SortedList();

            #region Parameter
            _sPara.Add("@Airlines", airlines);
            #endregion

            _dtResult = _db.GetDataTableBySP(_spName, _sPara);

            if (_dtResult.Rows.Count > 0)
            {
                imagename = _dtResult.Rows[0]["ImageName"].ToString();
            }
            return imagename;
        }

        private void CreateExceptionLog(Exception Ex, string strLocation)
        {
            String[] _fileContent = new String[6];
            _fileContent[0] = "Source : " + Ex.Source;
            _fileContent[1] = "Date Time : " + CE.Global.General.GetUTCDateTime().ToString();
            _fileContent[2] = "Stack Trace :" + Ex.StackTrace.ToString();
            _fileContent[3] = "Target Site : " + Ex.TargetSite.ToString();
            _fileContent[4] = "Location : " + "CE.Database.MyDatabase - " + strLocation;
            _fileContent[5] = "Message : " + Ex.Message;

            WriteExceptionLog("StreetDirectory_", _fileContent);
        }

        private void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                MyIO _newFile = new MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = CE.Global.General.GetUTCDateTime().Year.ToString("0000") + CE.Global.General.GetUTCDateTime().Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + CE.Global.General.GetUTCDateTime().Day.ToString("00") + CE.Global.General.GetUTCDateTime().Second.ToString("00") + CE.Global.General.GetUTCDateTime().Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }
    }
}